package com.elong.businesstravel.modules.home.hotel.search;

import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.content.DialogInterface;
import android.content.DialogInterface.OnDismissListener;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.InputType;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.view.View.OnFocusChangeListener;
import android.view.View.OnKeyListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.ExpandableListView;
import android.widget.ExpandableListView.OnChildClickListener;

import com.android.support.jhf.debug.DebugLog;
import com.android.support.jhf.dialog.CustomWaitDialog.OnKeyCancel;
import com.android.support.jhf.handlerui.HandlerPostUI;
import com.android.support.jhf.handlerui.HandlerToastUI;
import com.android.support.jhf.iphonetreeview.IphoneTreeView;
import com.android.support.jhf.utils.ToolUtils;
import com.elong.businesstravel.R;
import com.elong.businesstravel.base.baseactivity.BaseActivity;
import com.elong.businesstravel.base.utils.SaveUserOperate;
import com.elong.businesstravel.base.view.TitleNavBarView;
import com.elong.businesstravel.entitys.City;
import com.elong.businesstravel.modules.home.hotel.adapter.CityAutoCompleteAdapter;
import com.elong.businesstravel.modules.home.hotel.adapter.HotelCitySelecAdapter;
import com.elong.businesstravel.modules.home.hotel.widget.CitySearchAutoCompleteTextView;

/**
 * 酒店城市选择
 * 
 * @author lenovo
 * 
 */
public class HotelCitySelectActivity extends BaseActivity {

	private IphoneTreeView mListView;
	private HotelCitySelecAdapter mHotelCitySelecAdapter;

	private CitySearchAutoCompleteTextView mSearchAutoCompleteTextView;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_hotel_city_select);
		init();
	}

	@Override
	protected void init() {
		mListView = (IphoneTreeView) findViewById(R.id.listView);
		mListView.setFastScrollEnabled(true);

		mSearchAutoCompleteTextView = (CitySearchAutoCompleteTextView) findViewById(R.id.searchAutoCompleteTextView);
		mSearchAutoCompleteTextView
				.setInputType(InputType.TYPE_TEXT_FLAG_AUTO_COMPLETE);
		initAutoComplete(mSearchAutoCompleteTextView);

		City tempCity = SaveUserOperate.getHotelCity(mContext);

		mHotelCitySelecAdapter = new HotelCitySelecAdapter(mApplication,
				mApplication.mCity, tempCity);
		mListView.setAdapter(mHotelCitySelecAdapter);

		setTitleNavBar();

		setListener();
	}

	/**
	 * 初始化AutoCompleteTextView，最多显示5项提示，使 AutoCompleteTextView在一开始获得焦点时自动提示
	 * 
	 * @param field
	 *            保存在sharedPreference中的字段名
	 * @param auto
	 *            要操作的AutoCompleteTextView
	 */
	private void initAutoComplete(final AutoCompleteTextView auto) {
		showWaitDialog("正在加载请等待", new OnKeyCancel() {

			@Override
			public void onKeyCancelListener() {
				quit();
			}
		});
		new Thread(new Runnable() {

			@Override
			public void run() {
				final List<City> tempCity = new ArrayList<City>();
				tempCity.addAll(mApplication.mCity.searchCityList);
				HandlerPostUI.getHandlerPostUI(new Runnable() {

					@Override
					public void run() {
						final CityAutoCompleteAdapter cityAutoCompleteAdapter = new CityAutoCompleteAdapter(
								mContext, tempCity,
								mApplication.mCity.searchCityList);
						auto.setAdapter(cityAutoCompleteAdapter);
						// auto.setDropDownHeight(350);
						// auto.setDropDownVerticalOffset(5);
						auto.setThreshold(1);
						auto.setOnFocusChangeListener(new OnFocusChangeListener() {
							@Override
							public void onFocusChange(View v, boolean hasFocus) {
								// AutoCompleteTextView view =
								// (AutoCompleteTextView) v;
								// if (hasFocus) {
								// view.showDropDown();
								// }
							}
						});
						auto.setOnItemClickListener(new OnItemClickListener() {

							@Override
							public void onItemClick(AdapterView<?> arg0,
									View arg1, int arg2, long arg3) {
								City city = cityAutoCompleteAdapter
										.getCityByIndex(arg2);
								selectCitySaveFinish(city);
							}
						});
						hideWaitDialog();
					}
				});

			}
		}).start();

	}

	@Override
	protected void setListener() {

		Button searchButton = (Button) findViewById(R.id.searchButton);
		searchButton.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				String contain = mSearchAutoCompleteTextView.getText()
						.toString();
				List<City> rawCities = mApplication.mCity.searchCityList;
				List<City> tempCities = new ArrayList<City>();
				if (!TextUtils.isEmpty(contain)) {
					for (int i = 0; i < mApplication.mCity.searchCityList
							.size(); i++) {
						if (rawCities.get(i).cityName.startsWith(contain)) {
							tempCities.add(rawCities.get(i));
						} else if (rawCities.get(i).allCode.startsWith(contain)) {
							tempCities.add(rawCities.get(i));
						}
					}
				}
				if (0 == tempCities.size()) {
					HandlerToastUI.getHandlerToastUI(mContext, "没有找到您输入的城市");
				} else {
					mSearchAutoCompleteTextView.showDropDown();
				}
			}
		});
		mListView.setOnChildClickListener(new OnChildClickListener() {

			@Override
			public boolean onChildClick(ExpandableListView parent, View v,
					int groupPosition, int childPosition, long id) {
				City city = (City) mHotelCitySelecAdapter.getChild(
						groupPosition, childPosition);
				selectCitySaveFinish(city);
				return false;
			}
		});
	}

	/**
	 * 选中城市保存退出
	 * 
	 * @param city
	 */
	private void selectCitySaveFinish(City city) {
		// 保存选中城市
		SaveUserOperate.setHotelCity(mContext, city);

		Intent intent = new Intent();
		intent.putExtra("city", city);
		setResult(RESULT_OK, intent);
		quit();
	}

	@Override
	protected void setTitleNavBar() {

		TitleNavBarView titleNavBarView = (TitleNavBarView) findViewById(R.id.titleNavBarView);
		titleNavBarView.setMessage("选择城市");
		titleNavBarView.setTitleBackground(R.color.bg_title_dialog);
		titleNavBarView.setLeftButtonImageString(0, "取消", R.color.text_blue);
		titleNavBarView
				.setLeftButtonOnClickListener(new View.OnClickListener() {

					@Override
					public void onClick(View v) {
						quit();
					}
				});
		titleNavBarView.setRightButtonVisibility(View.INVISIBLE);
	}

	private void quit() {
		finish();
		overridePendingTransition(R.anim.activity_alpha_fixed,
				R.anim.activity_top_bottom_exit_anim_translate);
	}

	@Override
	public boolean dispatchKeyEvent(KeyEvent event) {
		return super.dispatchKeyEvent(event);
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			quit();
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
	}
}
